package com.sample.seata.service.impl;

import com.sample.seata.dao.UserDao;
import com.sample.seata.service.UserService;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.MissingFormatArgumentException;

@Service
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserDao productDao;

    @Override
    @Transactional // 开启新事物
    public void validUser(Long userId) throws Exception {
        logger.info("[validUser] 当前 XID: {}", RootContext.getXID());

        // 检查库存
        String name = productDao.getUser(userId);
        if (StringUtils.isEmpty(name)) {
            logger.warn("[validUser] {} 用户不存在！", userId);
            throw new MissingFormatArgumentException("用户不存在！");
        }

        // 更新用户下单次数
        productDao.updateCount(userId);

        logger.info("[validUser] 用户校验通过！");
    }

}
